class Admin::ProductAsController < Admin::AdminController
  skip_before_action :store_previous_url, only: [:search, :create, :update, :destroy]

  def index
    @product_as = ProductA
    @product_as = ProductA.filter(params[:category], params[:financing]) if params[:category] || params[:financing]
    @product_as = @product_as.order(created_at: :desc).page params[:page]
    gon.products = @product_as.map(&:as_my_json)
  end

  def search
    @product_as = ProductA.search(params[:keyword]).order(created_at: :desc)
    render json: @product_as.map(&:as_my_json)
  end

  def show
    @product_a = ProductA.find(params[:id])
  end

  def new
    gon.product_a = ProductA.new.to_json
  end

  def create
    @product_a = ProductA.new(product_a_params)
    if @product_a && @product_a.save
      @product_a.updateScreenshot params[:screenshots], params[:delete_image]
      render json: { product: @product_a, screenshots: @product_a.screenshots }
    else
      render json: { error: errors }
    end
  end

  def edit
    @product_a = ProductA.find(params[:id])
    gon.product_a = @product_a.to_json
    gon.screenshots = @product_a.screenshots.to_json
  end

  def update
    @product_a = ProductA.find(params[:id])
    if @product_a && @product_a.update(product_a_params)
      @product_a.updateScreenshot params[:screenshots], params[:delete_image]
      render json: { product: @product_a, screenshots: @product_a.screenshots }
    else
      render json: { error: errors}
    end
  end

  def destroy
    @product_a = ProductA.find(params[:id])
    @product_a.destroy
    redirect_back_or_default admin_product_as_path
  end

  def add_screenshot
    @product_a = ProductA.find(params[:id])
    shot = @product_a.screenshots.create(file: params[:file])
    render json: { id: shot.id, url: shot.file.url }
  end

  private
  def product_a_params
    product_params = params.require(:product_a).permit(:logo, :name, :summary,
                                      :description, :published_at, :url,
                                      :category, :user_id,{ contacts: [:name, :position, :email, :mobile] },
                                      { founders: [:name, :position, :email, :mobile] },
                                      { financings: [:stage, :amount, :invertor, :date] }, { cowork_records: [:mode, :staff, :date, :note] },
                                      { editor_comments: [:comment, :editor] }, :innoaward_id)
  end

  def errors
    errors = @product_a.errors.messages.keys.inject([]) do |sum, e|
      error = @product_a.errors.messages[e]
      error[0] = e.to_s + error[0]
      sum + error
    end
  end
end
